#include "util.h"
int main()
{
    signal(SIGPIPE,SIG_IGN);
	int sockfd,client_fd;
	struct sockaddr_in my_addr;
	struct sockaddr_in remote_addr;
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
	{
		perror("socket create failure!");
		exit(1);
	}
    memset(&my_addr,0,sizeof(my_addr));
	my_addr.sin_family=AF_INET;
	my_addr.sin_port=htons(SERVPORT);
	my_addr.sin_addr.s_addr=INADDR_ANY;
	if(bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))==-1)
	{
		perror("bind error!");
		exit(1);
	}
	if(listen(sockfd,BACKLOG)==-1)
	{
		perror("listen error!");
		exit(1);
	}
    printf("\nStart listening\n");
    while(1)
    {
        printf("\nlistening\n");
        int sin_size=sizeof(struct sockaddr_in);
        if((client_fd=accept(sockfd,(struct sockaddr *)&remote_addr,(socklen_t *)&sin_size))<0)
        {
            perror("accept error!");
            continue;
        }
        printf("received a connection from %s",inet_ntoa(remote_addr.sin_addr));
        int recvbytes=-1;
        char *buf=(char*)malloc(MAXDATASIZE*sizeof(char));
        string errorInfo;
        if(read_data(client_fd,buf,MAXDATASIZE,errorInfo)==-1)
        {
            perror("recv error!");
            return 1;
        }
        std::cout<<std::endl<<"read_data over! "<<buf+MAXDATASIZE-4<<std::endl;
     /* 
        while(1)
        {
            if((recvbytes=recv(client_fd,buf,MAXDATASIZE,0))<0)
            {
                perror("recv error!");
                exit(0);
            }
            buf[recvbytes] = '\0';
            printf("Received: %s\n",buf);
            if(strncmp(buf,"bye",recvbytes)==0) break;
        }
     */
        close(client_fd);
    }
}
